package com.wx.wxpush.job;

import com.wx.wxpush.mapper.CornTaskMapper;
import com.wx.wxpush.service.PushService;
import com.wx.wxpush.util.CronUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.wx.wxpush.util.CronUtil.getCron;

@Configuration
@EnableScheduling
public class scheduler implements SchedulingConfigurer {
    @Autowired
    private CornTaskMapper cornTaskMapper;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private PushService pushService;
    private ScheduledTaskRegistrar taskRegistrar;
    int i = 0;
    //定时任务方法
    private void schedulerMethod() {
        System.err.println("执行定时任务逻辑"+ LocalDateTime.now().toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        System.out.println("执行任务");
    }

    //每次执行完定时任务，都会重新执行一次configureTasks方法，根据参数重新设定定时器的执行时间
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select openid,id,cronmoring,cornnight from cron_default ");
        System.out.println(maps+"mapssss");
        List<TriggerTask> list = new ArrayList<>();

        maps.forEach(t -> {
            TriggerTask triggerTask = new TriggerTask(() -> {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                String dateStr = LocalDateTime.now().toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
                try {
                    Date date = simpleDateFormat.parse(dateStr);
                    String crons=getCron(date);
                    System.out.println(crons+"cron表达");
                    //这里写推送方法
                    pushService.goodMoringOk(crons);
                    pushService.goodNightOk(crons);

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                System.out.println("执行定时任务：" + LocalDateTime.now().toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                CronUtil cronUtil =new CronUtil();
                // pushService.goodMorning();

            }, triggerContext -> {
                // System.out.println("执行Cron早上的:"+t.get("cronmoring").toString()+",id="+t.get("id").toString()+",openid="+t.get("openid").toString());
                //如果需要动态的指定当前定时任务的执行corn。这里可以增加一步，查询数据库操作。如果任务corn不需要精确修改，corn可进行缓存。到期在去查询数据库。这里根据读者的需求自行取舍。

                System.out.println("近期这个");
//                if(t.get("cronmoring").toString().equals("")||  t.get("openid").toString().equals("")){
//                   return new CronTrigger("0 0 0 31 12 ? ").nextExecutionTime(triggerContext);
//               }else {
//               pushService.goodMorningtest(t.get("openid").toString(),t.get("cronmoring").toString());
                return new CronTrigger(t.get("cronmoring").toString()).nextExecutionTime(triggerContext);
//               }
                //return new CronTrigger(t.get("cronmoring").toString()).nextExecutionTime(triggerContext);

            });
            list.add(triggerTask);
            System.out.println("进阿里");
            taskRegistrar.setTriggerTasksList(list);
            this.taskRegistrar = taskRegistrar;

//                //2.设置执行周期(Trigger)
//                triggerContext -> {
//                    //2.1 从数据库获取执行周期
//                    //这里的意思是数据库查出对应的cron属性
//                    //String cron = sysParamConfigRest.getParamValue("TrackScheduler_cron");
//                    List<String> crons = cornTaskMapper.selectList();
//                    i++;
//                    System.out.println(crons.size()+"size");
//                    if(i==crons.size()-1){
//                        i=0;
//                    }
//                    List list = new ArrayList();
//
//
//                    for (String cron : crons) {
//                        list.add(cron);
//
////                        //2.2 合法性校验.
////                        if (StringUtils.isBlank(list.get( 1).toString())) {
////                            // Omitted Code ..
////                            System.out.println("trackScheduler定时器的cron参数为空！！！！！");
////                            //如果为空则赋默认值
////                            cron = "0 0 /1 * * ? ";
////                        }
//                        //2.3 返回执行周期(Date)
//                    }
//
//                    for(int o=0;o<list.size();o++){
//                        System.out.println(i-1);
//                        return new CronTrigger(list.get(i-1).toString()).nextExecutionTime(triggerContext);
//                    }
//
//                       // return new CronTrigger(list.get(o).toString()).nextExecutionTime(triggerContext);
//
//                    return null;
//                }
        });

    }
}